<script setup lang="ts">
import type { LoginUser } from '@/types/data'
// import type { AxiosError } from 'axios'
import { reactive } from 'vue'
import { login } from '@/api/user'
import { useRouter } from 'vue-router'
import useTokenStore from '@/stores/token'
// import { Toast } from 'vant'
import { showSuccessToast, showFailToast } from 'vant'
import 'vant/es/toast/style'
// import { Notify } from 'vant'
// import 'vant/es/notify/style'
const { updateToken } = useTokenStore()
const router = useRouter()
const UserForm = reactive<LoginUser>({
  username: '',
  password: ''
})

const onSubmit = async (values: LoginUser) => {
  console.log(values)
  try {
    const res = await login(values)
    console.log(res)
    updateToken(res.data.token) // 设置token
    // Toast.success('登录成功')
    // Notify({ type: 'success', message: '注册成功' })
    showSuccessToast('登录成功')
    router.push('/') // 跳转到主页
  } catch (error) {
    // const e = error as AxiosError
    console.log(error)
    // Notify({ type: 'danger', message: e.message })
    // Toast.fail('登录失败')
    showFailToast('登录失败')
  }
}
</script>
<template>
  <van-nav-bar title="登录"></van-nav-bar>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="UserForm.username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[
          { required: true, message: '请填写用户名' },
          {
            pattern: /^\w{6,16}$/,
            message: '用户名格式不正确'
          }
        ]"
      />
      <van-field
        v-model="UserForm.password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          {
            pattern: /^\w{6,16}$/,
            message: '用户名格式不正确'
          }
        ]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit"> 登录 </van-button>
    </div>
    <van-row justify="end" style="margin-right: 20px">
      <router-link class="link" to="/register">没有账号?去注册</router-link>
    </van-row>
  </van-form>
</template>
<style></style>
